package com.geyue.core.service.impl;

import com.geyue.common.base.service.impl.BaseServiceImpl;
import com.geyue.common.toolbox.result.Res;
import com.geyue.common.util.DateUtils;
import com.geyue.common.util.ExcelBean;
import com.geyue.common.util.ExcelUtil;
import com.geyue.common.util.StrUtils;
import com.geyue.core.mapper.BusinessMapper;
import com.geyue.core.mapper.ProductMapper;
import com.geyue.core.mapper.ProductPropMapper;
import com.geyue.core.model.Business;
import com.geyue.core.model.ProductProp;
import com.geyue.core.service.BusinessService;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lyon on 2017/3/27.
 */
@Service
public class BusinessServiceImpl extends BaseServiceImpl<Business> implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private ProductPropMapper propMapper;
    @Autowired
    private ProductMapper productMapper;


    @Override
    public Res submit(Business business) {

//        Product product = productMapper.selectByPrimaryKey(Integer.valueOf(business.getProduct()));

        Business record = new Business();
        record.setName(business.getName());
        record.setIdCard(business.getIdCard());
        record.setProduct(business.getProduct());
        record.setMoney(business.getMoney());

        Business isExits = businessMapper.selectOne(record);

        if (isExits != null) {
            String remark = business.getRemark();
            if (StrUtils.isEmpty(remark))
                return Res.fail("请输入备注!");
        }

//        List<ProductProp> props = propMapper.getByPid(Integer.valueOf(business.getProduct()));
//
//        Integer integral = 0;
//        Integer money = business.getMoney();
//
//        for (ProductProp prop : props){
//            if(money > prop.getMin() && money <= prop.getMax() ){
//                integral = new Double(money * 10000 * prop.getValue() / 100).intValue();
//            }
//        }

        business.setIsOk(Business.submit);
//        business.setIntegral(integral);

        if (businessMapper.insertSelective(business) > 0)
            return Res.success("请求成功!");

        return Res.fail("请求失败!");
    }

    @Override
    public List<Business> getListByUid(Integer uid,Integer year,Integer quarter) {
        return businessMapper.orderByTime(uid,year,quarter);
    }

    public void export(HttpServletRequest request, HttpServletResponse response, String start, String end) {
        Date startTime = DateUtils.format(start + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        Date endTime = DateUtils.format(end + " 59:59:59", "yyyy-MM-dd HH:mm:ss");

        try {
            List<Business> list = businessMapper.excel(startTime, endTime);
            ExcelBean excelBean = export(list);
            ExcelUtil.download(request, response, excelBean);
        } catch (Exception e) {
            e.printStackTrace();
            ExcelUtil.toErrorPage(response, request, "/500");
        }
    }

    /**
     * 封装excelBean
     *
     * @return
     * @throws Exception
     */
    private ExcelBean export(List<Business> list) throws Exception {
        ExcelBean excelBean = new ExcelBean();
        excelBean.setNum(0);
        excelBean.setName("业绩审核");
        excelBean.setSheetName("业绩审核");
        excelBean.setHeaderCenter("业绩审核");
        String[] tableHeader = new String[]{"ID","姓名", "身份证", "手机号", "类型", "金额", "贷款时间", "支行", "地区", "备注", "领导","是否通过审批(1/2)","未通过原因"};
        excelBean.setTableHeader(tableHeader);
        List<Object[]> sheetData = new ArrayList<Object[]>();
        excelBean.setSheetData(sheetData);
        excelBean.setColWidth(new Integer[]{50 * 60, 50 * 60, 50 * 100, 50 * 80, 50 * 60, 50 * 60, 50 * 80, 50 * 150, 50 * 150, 50 * 150, 50 * 80,50 * 80,50 * 200});
        for (Business item : list) {
            Object[] content = new Object[13];
            content[0] = item.getId();
            content[1] = item.getName();
            content[2] = item.getIdCard();
            content[3] = item.getMobile();
            content[4] = item.getProduct();
            content[5] = item.getMoney();
            content[6] = item.getLoanTime();
            content[7] = item.getArea();
            content[8] = item.getAddr();
            content[9] = item.getRemark();
            content[10] = item.getManager();
            content[11] = "";
            content[12] = "";
            sheetData.add(content);
        }
        return excelBean;
    }


    @Override
    public Res getTotal(Integer year,Integer quarter,Integer uid) {
        NutMap data = new NutMap();

        List<Business> count = businessMapper.count(year,quarter,uid);
        Integer totalIntegral = 0;
        Double totalMoney = new Double(0);

        for (Business item : count) {
            List<ProductProp> props = propMapper.getByPid(Integer.valueOf(item.getProduct()));
            Integer integral = 0;
            Double money = item.getMoney();

            for (ProductProp prop : props) {
                if (money > prop.getMin() && money <= prop.getMax()) {
                    integral = new Double(money * 10000 * prop.getValue() / 100).intValue();
                }
            }

            totalMoney += money;
            totalIntegral += integral;
        }

        data.put("integral",totalIntegral);
        data.put("money",totalMoney);

        return Res.success("",data);
    }

    @Override
    public Res readExcel(MultipartFile file) {
        try {
            List<NutMap> list = ExcelUtil.readExcel(file);

            for (NutMap item : list){
                Integer id = item.getInt("id");
                Integer isOk = item.getInt("isOk");
                String because = item.getString("because");
                Business business = new Business();
                business.setId(id);
                business.setIsOk(isOk);
                business.setBecause(because);
                businessMapper.updateByPrimaryKeySelective(business);
            }

            return Res.success("操作成功!");
        } catch (IOException e) {
            e.printStackTrace();
            return Res.fail("系统异常,稍后重试!");
        }
    }
}
